//
//  NewMessageDidExistEventProcessor.swift
//  app_rn_frontend
//
//  Created by 鱼涛 on 2017/12/14.
//  Copyright © 2017年 Facebook. All rights reserved.
//

import Foundation
import WCDBSwift

class NewMessageDidExistEventProcessor: EventProcessorProtocol{
  static let instance = NewMessageDidExistEventProcessor()
  
  private init(){}
  
  func process(params: Dictionary<String, Any>?) throws{
    do{
      guard AppStatusManager.instance.userLoginStatus.0 && AppStatusManager.instance.userLoginStatus.1 != nil && AppStatusManager.instance.userLoginStatus.1 != 0 else {
        throw ProcessError.LoginStatusError
      }
      
      guard let pathForUserDB = AppStatusManager.instance.urlForUserDB?.path else{
        throw ProcessError.InvalidParamError
      }
      
//      let db = try Connection(pathForUserDB)
        let db = try Database(at: pathForUserDB)
      let message = try db.getValue(on: Message.CodingKeys.syncKey.asColumn().max(), fromTable: Message.table)
      let maxSyncKey = Int(message.int32Value)
//      let maxSyncKey = try db.scalar(Message.table.select(Message.syncKey.max)) ?? 0
      if(AppStatusManager.instance.userLoginStatus.0 == true && AppStatusManager.instance.userLoginStatus.1 != nil){
        ConnectionManager.instance.syncMessage(userId: AppStatusManager.instance.userLoginStatus.1!, syncKey: maxSyncKey)
      }
    }catch{
      throw error
    }
  }
}
